import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:tiktokadult/hj_utils/api_service/common_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/text_util.dart';
import 'package:path/path.dart' as path;
import 'package:provider/provider.dart';

import '../assets_tool/app_colors.dart';
import '../config/address.dart';
import '../config/config.dart';
import '../hj_model/message/msg_count_model.dart';
import '../hj_model/message/services_model.dart';
import '../hj_page/zaixiankefu/chat_widget/chat_core/network/connection/socket_manager.dart';
import '../hj_page/zaixiankefu/chat_widget/chat_model/userModel.dart';
import '../tools_base/cache/image_cache_manager.dart';
import '../tools_base/global_store/store.dart';
import '../tools_base/widget/LoadingWidget.dart';
import 'flutter_base.dart';

final csManager = CSManager();

/// 客服管理类
class CSManager {
  Future<void> init() async {
    var model = await _getServices();

    if (model == null) {
      showToast("获取客服信息失败");
      return;
    }
    var user = globalStore.getMe();
    var base64 = '';
    try {
      //正加载一次  确保能在缓存中读到数据，待优化
      var commonImgPath = getImagePath(user?.portrait ?? "", false, false, width: 100, height: 100);
      // ImageLoader.withP(ImageType.IMAGE_NETWORK_HTTP, address: commonImgPath).load();
      // var commonImgPath = path.join(Address.baseImagePath, user.portrait);
      // var a = await ImageCacheManager().getFileFromCache(commonImgPath ?? '');
      var f = await ImageCacheManager().getSingleFile(commonImgPath);
      List<int> imageBytes = await f.readAsBytes();
      base64 = base64Encode(imageBytes);
    } catch (e) {}

    //"https://zsjs.qyukwnk.com"
    var url = Address.baseHost! + model!.sign!;
    // var url = "https://qhapi.5igww.cn/kefu/customer/im?sign=b2b37f2e09b525ba3f80349871be3cefe7ddbc3ca8a6565ea2f02485a97f8f395c3bac3e8df826fb906ca3d1c6b3431f2a793b362817b8ec80b179fc001ad7a5d50adb4d18f6b7c8b796bf4613a91d6cf8d858e89903700fa0c6a7316d0ef01668f8e1d07324e4278981699468af0e855e284ff5bcea00adb0bdaa4e50bcb6065be2a7675b8a796bccff3cc059a83f913b0cac63d47645093a4bb1a4fb6b6e8c43bd803dc02cdd2825b11461f5c8cf7c&appId=8818714660&theme=theme1";
    var baseUrl = Address.baseHost;
    // var url = "https://zsjs.qyukwnk.com" + model?.sign ?? '';
    // var baseUrl = "https://zsjs.qyukwnk.com";

    // var url = 'http://183.61.126.215:9090/customer/im?sign=346de818698fed14e44cc49a9a2d19a7243a809a261bb81485f99ac354e1f8ddc0800fb1fb821997af1a4ba290e7f6beb07d3e55a5b15e9db2ac6bd1cb1447635c727be5e58c4e36e9834980c18f10cb&appId=9189155602&protoType=1&pType=201';
    // var url = 'http://163.53.216.122:8081/kefu/customer/im?sign=346de818698fed14e44cc49a9a2d19a7243a809a261bb81485f99ac354e1f8ddc0800fb1fb821997af1a4ba290e7f6beb07d3e55a5b15e9db2ac6bd1cb1447635c727be5e58c4e36e9834980c18f10cb&appId=9189155602&protoType=1&pType=201';
    // var baseUrl = 'http://183.61.126.215:8080';
    print("socket拼接地址:" + url);
    var param = KefuUserModel(
        userId: user?.uid!.toString() ?? "",
        username: user?.name ?? '',
        baseUrl: baseUrl ?? "",
        isVoice: model!.isVoiceActive ?? false,
        connectUrl: url,
        backgroundColor: Colors.white,
        avatar: base64,
        faqApi: model!.faq!,
        appBarColor: AppColors.primaryColor,
        // faqHeadcommonImgPath: AssetsSvg.MESSAGE_IC_ONLINE_CUSTOMER_SERVICE,
        primaryColor: Colors.red,
        checkConnectApi: model?.check ?? "/kefu/api/play/unread");
    SocketManager().model = param;
    SocketManager().getMsg = (int count) {
      Future.delayed(Duration(milliseconds: 200), () {
        var context = FlutterBase.appContext;
        Provider.of<MsgCountModel>(context!, listen: false).setCount(count);
      });
    };
    SocketManager().requestIsConnect();
  }

  Future<ServicesModel?> _getServices() async {
    LoadingWidget? loadingWidget;
    try {
      loadingWidget ??= LoadingWidget(title: "加载中...");
      loadingWidget.show();
      var model = await CommonService.getServices();
      loadingWidget.cancel();
      return model;
    } catch (e) {
      loadingWidget?.cancel();
      return null;
    }
  }

  Future openServices(BuildContext context) async {
    if (SocketManager().model == null) {
      await init();
    }
    return SocketManager().jumpToChatWidget(context).then((value) {
      // if (Config.isGameSurface) {
      //   FBroadcast.instance().broadcast(Config.showFloating);
      //   AutoOrientation.landscapeAutoMode();
      //   if (Config.webView != null) {
      //     Config.webView?.android.resume();
      //   }
      // }
    });
  }

  String getImagePath(String commonImgPath, bool fullImg, bool isGauss, {double? width, double? height}) {
    if (TextUtil.isEmpty(commonImgPath)) {
      //l.e("image", "getImagePath()...commonImgPath is empty",
      // stackTrace: StackTrace.current);
      return "";
    }
    if (commonImgPath.startsWith("http") || commonImgPath.startsWith("https")) {
      return commonImgPath;
    }

    ///需要大图且不高斯
    if (fullImg && !isGauss) {
      commonImgPath = path.join(Address.baseImagePath ?? "", commonImgPath);
      return commonImgPath;
    }
    String rootPath = path.join(Address.baseImagePath ?? "", "imageView/1");
    if (!fullImg && (width?.isInfinite ?? false) && (width?.isNaN ?? false) && (height?.isNaN ?? false) && (height?.isInfinite ?? false)) {
      rootPath = path.join(rootPath, "w/$width/h/$height");
    }
    if (isGauss) {
      rootPath = path.join(rootPath, "s/${Config.GAUSS_VALUE}");
    }
    rootPath = path.join(rootPath, commonImgPath);
    return rootPath;
  }
}
